Loop through the geometry's index and set each value

I have managed to create the pattern shown in the image successfully. Currently, I am looking for a way to automate this process. Specifically, every second square needs to be mirrored.

If you have any suggestions on an easier approach, please share them with me.

image

This is how my code is structured:

// Generating vertices for widthSegments
for (let x = 0; x < world.plane.widthSegments; x++){
   for (let y = 0; y < world.plane.heightSegments; y++){
   vertices.push(x, y, 0)      // 0, 4, 8,  12, 16, 20, 24, 28, 32, 
   vertices.push(x+1, y, 0)    // 1, 5, 9,  13, 17, 21, 25, 29, 33, 
   vertices.push(x+1, y+1, 0)    // 2, 6, 10, 14, 18, 22, 26, 30, 34, 
   vertices.push(x, y+1, 0)  // 3, 7, 11, 15, 19, 23, 27, 31, 35, 
   }
}
planeMesh.geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(vertices), 3))

planeMesh.geometry.setIndex([  // The desired automatic generation
   0,  1,   3,   3,  1,  2,  
   2,  6,   3,   3,  6,  7,    
   7,  6,  11,  11,  6, 10,  
   10, 14, 11,  11, 14, 15,  
    
   1,  17, 18,  18,  2,  1,  
   2,  18,  6,   6, 18, 22,  
   6,  22, 26,  26, 10,  6,  
   10, 26, 14,  14, 26, 30,  
    
   17, 33, 18,  18, 33, 34,  
   18, 34, 38,  38, 22, 18,  
   22, 38, 26,  26, 38, 42,  
   26, 42, 46,  46, 30, 26,  
    
   33, 49, 50,  50, 34, 33,  
   34, 50, 38,  38, 50, 54,  
   38, 54, 58,  58, 42, 38,  
   42, 58, 46,  46, 58, 62,  
]);

Answer №1

To optimize PlaneGeometry, you can recalculate its index using the provided code snippet.

body{
  overflow: hidden;
  margin: 0;
}
<script type="module">
import * as THREE from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9e82988f8faadac4dbd9dcc4da">[email protected]</a>";
import { OrbitControls } from "https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6c2dec4d3d3f686988785809886">[email protected]</a>/examples/jsm/controls/OrbitControls";

let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(
  60,
  innerWidth / innerHeight,
  0.1,
  100
);
camera.position.set(0, 0, 10);
let renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener("resize", (event) => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});

let controls = new OrbitControls(camera, renderer.domElement);

let g = new THREE.PlaneGeometry(10, 10, 10, 10);
recalcIndex(g);
let m = new THREE.MeshBasicMaterial({ color: "aqua", wireframe: true });
let o = new THREE.Mesh(g, m);
scene.add(o);

renderer.setAnimationLoop(() => {
  renderer.render(scene, camera);
});

function recalcIndex(plane) {
  let w = plane.parameters.widthSegments;
  let h = plane.parameters.heightSegments;
  let idx = [];
  for (let y = 0; y < h; y++) {
    for (let x = 0; x < w; x++) {
      let a = x + ((w + 1) * y);
      let b = x + ((w + 1) * (y + 1));
      let c = (x + 1) + ((w + 1) * (y + 1));
      let d = (x + 1) + ((w + 1) * y); 
      
      if ((x + (y % 2)) % 2 == 0) {
        idx.push(a, b, d, b, c, d);
      } else {
        idx.push(b, c, a, c, d, a);
      }
      
    }
  }
  plane.setIndex(idx);
}

</script>

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

Employing a lexicon of hexadecimal color code values to harmonize CSS styles

I have a unique requirement where I need to utilize a dictionary of HTML color codes and then apply those colors as styles. It's an interesting challenge! Here is an example of how my color dictionary looks like: const colorCodes = { red: ...

Button in Laravel Vue JS staying enabled after redirection

I am facing an issue with a button on my webpage. Whenever the button is clicked, it should become disabled and have aria-disabled="true" added to it. However, upon page reload, the button does not remain disabled even though I pass a boolean true value to ...

What is the best way to adjust the height and width of a div when it comes into view through scrolling?

How can I automatically and frequently change the size of my div when it is scrolled into view? HTML <div id="contact" class="fadeInBlock"> <div class="map"> <div class="pointer"> <div class="dot"></div& ...

Hide the HTML DIV without altering the position of the current div

My goal is to conceal elements 1, 3 and 2 & 4 without changing their position. div{ width: 10%; float: left; } <div style="background-color: blue"><p>1</p></div> <div style="background-color: yellow"><p>2</ ...

Fixing the error "require() is not defined" when trying to call a function from JavaScript to Node.js

As I work on building my website, I discovered that Javascript lacks a built-in way to communicate with a database. Through my research, I came across node.js and decided to implement it. Here is a snippet of the code I've written: var mysql; var con; ...

Tips for adjusting the height of a div using the slideToggle function for expanding and collapsing content

Is there a way to modify my code in order to adjust the height of a <div> using slideToggle()? The current implementation works almost correctly, with one minor issue. When I click on one "read_more" and then click on another, it does not behave as e ...

Activate a function when the VueJS countdown timer hits zero

I've successfully created a countdown timer in the template that decrements a number perfectly. Now, I'm facing the challenge of triggering a function declared within the methods section once the countdown reaches 0. Despite attempting to check i ...

Concealing option value based on ng-if conditions in AngularJS: A guide

I am designing an Input form with two input fields that need to be compared and values displayed if a certain condition is met. The input fields are: <td class="td_label"><label>Client Age :</label></td> <td class="td_input"> ...

Angular HttpClient not recognizing hashtag

I'm trying to make a REST API call, but running into issues with the developerId parameter being sent incorrectly: let developerId = "123#212"; let url = \`\${Constants.BASE_URL}\${marketId}/developers/\${developerId}\`; retur ...

React - Insert a Component in-between two already rendered components

As a React beginner, I am working on creating a dynamic form that allows users to add and remove fields. However, I encountered an issue with rendering after adding a new row (field). Below is my Row Component, which serves as a template filled with props ...

Examining the Similarities Between Two Arrays using ng-repeat

I am attempting to generate multiple checkboxes using ng-repeat from Array1, and I want to apply the "checked" attribute (using ng-checked) to specific checkboxes based on whether there is a match in Array2. Here are the elements in array1 within the cont ...

Retrieving a value from an array at random to assign to a different variable

I have different options for a specific variable depending on the scenario --> var lowSpeed = Math.random() * (45 - 30) + 30; var mediumSpeed = Math.random() * (60 - 45) + 45; var highSpeed = Math.random() * (80 - 60) + 45; var highwaySpeed = Math.rando ...

What is the best way to apply hover effects to all links except the one being hovered over, using a combination of javascript, jquery,

While browsing the web, I came across a fascinating hover effect that I'm eager to replicate in a website's navigation bar. This effect doesn't just change the link you hover over, but it alters every other link in a unique way. When hoverin ...

Switching database connections based on routes in express.js using sequelize

Can the database connection in sequelize be modified based on the route? For instance, Users can access 2 different installations on a website: - example.com/foo - example.com/bar When users log in, they are directed to example.com/foo. To view all th ...

Responsive mode causing navbar to break

After creating my web portfolio, I encountered an issue when viewing it on my phone. The navbar collapses but is not properly aligned and there is extra space on the right side of the viewport in the hero section that I can't seem to fix. Portfolio L ...

Find the average value of an array containing objects

Imagine I have an array of objects like this: const BookDetails = [ { bookName: 'Harry Pottar', readingTime: 10663 }, { bookName: 'Harry Pottar', readingTime: 10986 }, { bookName: 'kaptura Tech', readingTime: 7034 } ] I ...

The Quasar application does not eliminate console.log() statements during production builds

I've been facing difficulties in removing the console.log() from my Quasar app for production builds. Despite checking solutions on various platforms like StackOverflow, Quasar forums, and GitHub, I am still struggling to eliminate the console.log st ...

Locate within an HTML table (inside a specific td child tag) and conceal the row

I am trying to search for content within the H3 tag only, not the TD tag. If a result is found in the table, I want the corresponding TR to be hidden. -H3 is a child tag under TD. For example: <tr> <td> <h3>Example</h3> & ...

Best practices for organizing an array of objects in JavaScript

I have an array of objects with nested arrays inside, and I need to restructure it according to my API requirements. [{ containerId: 'c12', containerNumber: '4321dkjkfdj', goods: [{ w ...

Methods for sending an indexed array object back to a getJSON request with jquery

When sending an Indexed Array to a PhP file on the server side using getJSON, it seems like using an associated array may be a better choice. However, the indexed array works fine and the data is successfully received on the server. I am able to process th ...