Exploring the versatility of WebGL and Three.js with multiple materials on a single intricate grid structure

To enhance performance, I optimize by rendering the grid to a single THREE.Geometry() object using this loop:

build: function(){ 

  square = new THREE.Geometry();
  face = 0;

  for(r = 0; r < this["rows"]; r++)
   for(c = 0; c < this["cols"]; c++)

       // create square
       square.vertices.push(new THREE.Vector3(x, y, z));
       square.vertices.push(new THREE.Vector3(x + w, y, z));
       square.vertices.push(new THREE.Vector3(x + w, y - h, z));
       square.vertices.push(new THREE.Vector3(x, y - h, z));

       square.faces.push(new THREE.Face4(face + 0, face + 1, face + 2, face + 3));

       face += 4;
  // end of loops 

  // Add material to the entire grid.
  // How can individual colors be applied to each square?

  squareMaterial = new THREE.MeshBasicMaterial({
        color:"white",
        side:THREE.DoubleSide
  });

  grid = new THREE.Mesh(square, squareMaterial); 
  scene.add(grid);

Assuming there's a function that selects the vertices set (one square) from the grid (mesh), how do you then apply color specifically to this vertices set (square)?

Answer №1

When writing your code, keep in mind that you are creating a single object grid with one material. It is not possible to set a new material for just part of the object. One way around this limitation is to write your own shader and define attributes such as pos.x, pos.y, and texture. Another option could be to draw your grid in sections, although this may not be the best approach.

Answer №2

Firstly: start by generating a grid using a plane geometry with multiple segments (10x10):

let planeGeometry = new THREE.PlaneGeometry(100, 100, 10, 10);

Secondly: assign materialIndex to the desired face for changing the material color:

For example:

planeGeometry.faces[5].materialIndex = 1;

Please note that the default materialIndex is set to 0;

Next, create two or more materials and store them in an array:

let materialsArray = [
        new THREE.MeshBasicMaterial({color: 0xFF0000, side: THREE.DoubleSide}), // matIdx = 0
        new THREE.MeshBasicMaterial({color: 0x00FF00, side: THREE.DoubleSide}) // matIdx = 1
    ];

Then, create a multimaterial:

let multiMaterial = new THREE.MeshFaceMaterial(materialsArray);

Afterward, generate the mesh and add it to the scene:

grid = new THREE.Mesh(planeGeometry, squareMaterial); 
scene.add(grid);

I hope this explanation proves useful,

M.

PS:

You may need to rotate the planeGeometry 180 degrees around the X or Z axis - as the PlaneGeometry might be created with normals facing downward - although this is not certain.

If rotation is necessary, you can achieve it by:

planeGeometry.applyMatrix(new THREE.Matrix4().makeRotationX(Math.PI));

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

Techniques for linking <span> values to the radar chart's field titles using AngularJS or JQuery

Here is the code snippet containing a list of spans that are generated based on user input: <div id="tags" style="border:none"> <span class="tag" id="4"></span> <input type="text" id="inptags" value="" placeholder="Add max of 6 values ...

My attempts to load the .mtl and .obj files using THREE.js have been unsuccessful

I've been working on creating a 3D model viewer using three.js, but I'm encountering issues with loading .mtl and .obj files. Despite following a tutorial at , the only model that loads successfully is the female one. Here is the code snippet I ...

What is the best method for creating a fade effect on a div background?

I am trying to animate a div with the id #test from a 0 opacity background to an opacity of 0.7 using CSS rgba values, but for some reason, the .animate function is not working as expected. Here is my CSS: #test { background-color: rgba(0, 0, 0, 0); ...

The Comparison of $rootScope and services in AngularJS

Can you explain the differences between implementing a $rootScope function and a service in terms of security and performance? After reading this, I am curious. I have been trying to determine whether a specific global function for my app should be imple ...

Change the content of a selectbox dynamically with the help of jQuery and AJAX

Currently, I am exploring the best approach for a specific challenge: I have various categories, subcategories, sub-subcategories, and so on, that I need to display in separate select boxes. For instance, initially, the options may look like this: <sel ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

I am currently working on coding a function that will search an array to determine if a specific item is present. If the item is found, a variable will be set to true;

So, I have this array of prices for various items like bread, apple, noodles, beef, milk, and coke. const prices = [ ["bread", 20], ["apple", 50], ["noodles", 100], ["beef", 40], ["milk", 32], ["coke", 25], ]; And here's the JavaScript co ...

The expandable row remains open even after filtering the table with JavaScript

An expandable row in the table displays details of rows. I have implemented a JavaScript search and filter function to find specific row content. However, when using the search filter, it successfully shows results but does not expand the details as intend ...

I am having trouble retrieving any data when using jQuery to post JSON data

I am struggling with some HTML and JavaScript code. Here is what I have: <html> <head> </head> <body> <script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></sc ...

Is the return value a result of destructuring?

function display(): (number, string) { return {1,'my'} } The code above is displaying an error. I was hoping to use const {num, my} = print(). How can I correctly specify the return type? ...

Choose the dropdown item depending on the related text

I am currently working on a drop-down menu where each option has a value and associated text. The selected option is then displayed row by row in a table, with an edit button next to each row that allows the user to change the selection. I am trying to imp ...

Encountering issues when implementing react-router with the client-side library

After following the author's suggestion, I've successfully loaded the client-side library. The recommended method is to simply drop a <script> tag in your page and use the UMD/global build hosted on cdnjs. I have ensured that ReactRouter i ...

Looping through an array

I have created an array as shown below: iArray = [true, true, false, false, false, false, false, false, true, true, true, false, true, false, false, false, false, true] Condition check: If any value in this array is false, I will display an error messag ...

Retrieve initial elements from an array with the help of Node.js or JavaScript

let array = [[`animal`,`carnivours`], [`cow`,`milk`], [`plant`,`small`], [`fish`,`tank`]] console.log(array[0]); It seems that when trying to retrieve the first value from an array, we typically use array[0] to access all the first elements in the a ...

How to Retrieve a Targeted Element from a Multidimensional Array

I've got some data that looks like this: [[12, 23],[27,-6],[52, -32],[82, 11]] How can I access specific elements within these arrays? With a standard array like this: [a, b, c, d] It's easy to reference 'b' as arrayName[1]. But ho ...

Using Heroku to deploy NodeJS applications

I am facing an issue while trying to deploy my NodeJS project on Heroku. The project is a multiplayer game where, locally, both players enter the same map successfully. However, on Heroku, I am unable to get both players on the same map. Below is a snippe ...

Is it possible for an HTML5 video element to stream m3u files?

Hey there, I'm currently working on integrating a video player using the HTML5 video tag. The content I have is being provided by Brightcove and is in the form of an m3u file. Is it feasible to play this video using the HTML5 video tag? My understand ...

Exploring the World of Metaprogramming with AngularJS Filters

Can we generate filters dynamically in Angular? Below are some basic filters that extract specific properties from an array of objects. module.filter("firstAndLastName", function() { return function(input) { return input.map(function(obj) { ...

Creating an infinite SVG animation loop using JavaScript

elem = document.querySelectorAll("path"); function task(i) { setTimeout(function() { elem[i].animate({fill: 'green'}, { // timing options duration: 150, iterations: 1 }); }, 150*i); } for(var i=0;i<8;i++){ task(i); } < ...

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...