Creating copies of triangles in ThreeJS and then rotating each one separately

Here is the code snippet I am working with: https://pastebin.com/sxfmAAz9 (I'm using Pastebin to keep things concise as the code is a bit lengthy)

The goal of my project is to create a spiky plane by splitting it into widthsegments and heightsegments. After this, I iterate over each face and duplicate it to make it appear as if it's coming out of the plane with a slow rotation effect. While I have successfully achieved this, there seems to be an issue where the rotated triangles appear grouped together like part of the same mesh even though I'm creating new meshes for each face. Here's how I generate the triangles:

if (numberOfTriangles < possibleFloatingTriangles) {
  var randomIndices = [];

  while (randomIndices.length < possibleFloatingTriangles - numberOfTriangles) {
    var randomNumber = Math.ceil(Math.random()*150);
    if (randomIndices.indexOf(randomNumber) > -1) continue;
    randomIndices[randomIndices.length] = randomNumber;
  }

  scene.traverse(function (node) {
    if (numberOfTriangles >= possibleFloatingTriangles) return;

    if (node instanceof THREE.Mesh && node.geometry.type === "PlaneGeometry") {
      for(var i = 0; i < node.geometry.faces.length; i++) {
        if(randomIndices.indexOf(i) != -1) {
          var currentFace = node.geometry.faces[i];
          var triangleGeometry = new THREE.Geometry();

          var p1 = node.geometry.vertices[currentFace.a].clone();
          var p2 = node.geometry.vertices[currentFace.b].clone();
          var p3 = node.geometry.vertices[currentFace.c].clone();

          triangleGeometry.vertices.push(p1);
          triangleGeometry.vertices.push(p2);
          triangleGeometry.vertices.push(p3);

          var face = new THREE.Face3(0,2,1);

          triangleGeometry.faces.push(face);

          var triangleMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000, wireframe: showWireframe, specular: 0x0, morphTargets: true, flatShading: true, side: THREE.DoubleSide });
          var triangle = new THREE.Mesh(triangleGeometry, triangleMaterial);

          triangle.rotation.set(-Math.PI/2, Math.PI/2000, Math.PI); ;

          scene.add(triangle);
        }
      }
    }
  }
}

I'm looking for a way to make each individual triangle mesh rotate around itself instead of appearing grouped together. Currently, all the triangles seem connected when rotating, giving the impression of rotating a single plane rather than separate triangles. How can I achieve the desired individually rotating triangles effect?

Answer №1

The reason behind this phenomenon is that all triangles share the same origin at 0, 0, 0. As a result, when you rotate them, they appear connected. To address this issue, you should utilize the translate function on the geometry to reposition its vertices around the origin before resetting the mesh to its initial coordinates using the position property:

Consider a scenario where you aim to rotate a triangle around the designated point [5, 3, 0]:

// Apply translation to bring geometry to the origin
triangleGeometry.translate(-5, -3, 0);
var triangleMaterial = new THREE.MeshPhongMaterial({ color: 0xff0000, wireframe: showWireframe, specular: 0x0, morphTargets: true, flatShading: true, side: THREE.DoubleSide });
var triangle = new THREE.Mesh(triangleGeometry, triangleMaterial);
// Restore the mesh to its original position
triangle.position.set(5, 3, 0);

The method of determining the center for each triangle is left for you to figure out :)

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

Creating Space Around Content Using Padding in HTML

I'm currently working on creating a "Pad," but I am struggling to figure out how to do it. If you take a look at the Fiddle, you'll notice that the "Content" is padded intentionally. I know how to achieve this using a table. However, when inclu ...

Is it possible to navigate to the same route using the navigator in a React Native app?

One of my challenges involves a view called DynamicView. I am attempting to navigate to the same view (DynamicView) using different parameters in the navigator. this.props.navigator.push({ component: DynamicView, params: {} //Different params }) . ...

Using a combination of ASP.NET webpage and JavaScript, a dynamic webpage with a repe

I am new to using VB and integrating JavaScript. I have a simple question, but I'm having trouble figuring it out for some reason. I am struggling to properly construct an IF-statement. Can you please help me? I have searched and googled, but have no ...

Getting latitude and longitude from Google Maps in a React Native appHere are the steps to

Looking to retrieve the latitude and longitude from Google using React Native. As a newcomer to React Native, I have been unable to find any resources to address this issue. Any assistance would be greatly appreciated. Thanks! Thanks ...

Storing Japanese and Korean data in MySQL tables

I'm encountering an issue while trying to save data in my database, specifically with Japanese names. The error message I'm receiving is: Warning: #1366 Incorrect string value: '\xE3\x83\xA9\xE3\x83\x87...&apos ...

Are there specific methods within the Window object for accessing and modifying keys?

Is there an official mechanism to set/get keys on the Window object besides directly assigning values with window.myValue = 'something'? I'm looking for a method similar to: window.setValue('myKey', 'myValue') window.get ...

How can Prisma be used to create a model for a database table with a hyphen in its name?

One of the tables in my database has a hyphen in its name, for example, "user-cars". Unfortunately, I am unable to change the name to "user_cars". Is there any way for me to name the model as "user_cars" while still making it reference the "user-cars" ta ...

Issue found: Passing a non-string value to the `ts.resolveTypeReferenceDirective` function

Encountering the following error: Module build failed (from ./node_modules/ts-loader/index.js): Error: Debug Failure. False expression: Non-string value passed to ts.resolveTypeReferenceDirective, likely by a wrapping package working with an outdated res ...

Issues with AngularJS and UI-grid: the gridOptions are being overlooked by the grid

Having trouble with ui-grid disabling grid menu and renaming columns? Check out this plnkr I made: https://plnkr.co/edit/EGhvBGOJCKPzfupjCROx?p=preview In the script.js, I want my columns to be named 'banana', 'chrom', and 'positi ...

Finding the minimum value in a list and the maximum value in JavaScript

My current JavaScript list consists of dollar coin values: let x = [1.0, 2.5, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0, 5000.0] My challenge is finding an equation in JavaScript that will allow me to use the smallest number of coins to reach the desired max ...

Having trouble getting the .each() method to function properly in jQuery

Looking for a solution to a similar issue here. Currently, I am attempting to iterate through multiple forms on a webpage and perform various actions with those forms. However, I am facing some challenges in making it work. Below is the code I am using: ...

Angular Karma encountered an error: TypeError - It is unable to read the property '_id' as it is undefined

Encountering an issue while testing with karma jasmine, the error message appears as... TypeError: Cannot read property '_id' of undefined This is the Component.ts file: import { Component, OnInit } from '@angular/core'; import { ApiSe ...

determine the proportion of the item

My function is supposed to map an object to create new keys. The new key "percent" is meant to calculate the percentage of each value of the key "data". It should be calculated as the value divided by the sum of all values. However, for some reason, it&apo ...

What could be causing the hover effect to not work on the cards in my Svelte component? (HTML+CSS)

Greetings everyone! This is my debut post on this platform, and I'm in urgent need of assistance as I am relatively new to the world of programming. I've been trying tirelessly to implement a hover effect on these cards, but for some reason, it ...

The utilization of $(this) proves to be ineffective

I've been working on getting a script to add events to a specific DIV within a class using pep.js: $( ".drag" ).pep({ start: function() { $(".drag").addClass('color'); $('.drag').next(".text").fadeIn("slow"); ...

Steps for adding a row as the penultimate row in a table

There aren't many solutions out there that don't rely on jQuery, but I'm looking to avoid it. The row content needs to be generated dynamically. Here is my flawed approach: function addRow() { let newRow = '<tr><td>B ...

Discovering the worth of a key within a JSON file

Below is a JSON with objects containing artist and image values. I need a function that, given an artist name, will return the corresponding image value in the same object. All objects are enclosed in an array as a JSON. var iTunes_data = $([{ "titl ...

Hold on until the page is reloaded: React

My current setup includes a React Component that contains a button. When this button is clicked, a sidePane is opened. What I want to achieve is refreshing the page first, waiting until it's completely refreshed, and then opening the sidepane. Below i ...

How is it possible that the sensitivity of the mobile slideshow is malfunctioning specifically when accessed through the Chrome browser in React?

My React web app features a carousel component that functions perfectly on Firefox. However, in Chrome on mobile devices, when I swipe down the page, it interprets it as a horizontal swipe and switches slides on the slideshow. The library I am using is cal ...

How can we refresh an updatePanel on the main page from a popup using ASP.Net?

Looking for assistance, thank you in advance. I have two aspx pages - the first one is the main page with an updatepanel where I call the second page as a popup. I am looking for a way to update the updatepanel on the main page from the popup. Thank you f ...