Rearrange elements in an array

Currently, I have an array of sphere meshes and I am looking for a way to position them in a level. The meshes are currently set in a specific position (in the shape of a skeleton), but I would like to move the entire array and place it in a different location instead of moving each mesh individually. Is there a way to achieve this?

var meshJoints = [];
for (var i = 0 ; i < 25 ; i++)
{
    var geo = new THREE.SphereGeometry(0.02, 18, 18);
    var mat = new THREE.MeshPhongMaterial({color: 0xCCCCCC});
    var mesh = new THREE.Mesh(geo, mat);
    meshJoints.push(mesh);
}

Answer №1

To simplify your scene organization, group all your meshes together using a Group element and then manipulate the entire group.

var meshCollection = new THREE.Group();
for (var i = 0 ; i < 25 ; i++)
{
    var geometry = new THREE.SphereGeometry(0.02, 18, 18);
    var material = new THREE.MeshPhongMaterial({color: 0xCCCCCC});
    var mesh = new THREE.Mesh(geometry, material);
    meshCollection.add(mesh);
}

scene.add(group);
meshCollection.position.set(x, y, z); // changes to group position affect all children

A Group in Three.js serves as a container for multiple objects and can be transformed as a whole. Adjusting the position, rotation, or scale of a Group will automatically apply the same transformation to all its children. By setting the position of the Group, you can relocate all the Mesh elements simultaneously.

Answer №2

Technique 1

By combining these spheres using an additional geometric method:

const newGeometry = new THREE.Geometry();
newGeometry.merge(shape1.geometry, shape1.matrix);

You can simply adjust the position of the merged object and they will all move accordingly. For reference, check out this codepen: https://codepen.io/ThanosSar/pen/JjRgyQz

For more insights, refer to the three.js documentation:

:

.merge ( geometry : Geometry, matrix : Matrix4, materialIndexOffset : Integer ) : null
Merge two geometries or geometry and geometry from object (using object's transform)

Technique 2

UPDATE : (this method allows meshes to remain individual and movable separately)

Another approach is to establish an object3d hierarchy simply by:

mainMesh.add(shape1)

For demonstration, see this codepen : https://codepen.io/ThanosSar/pen/VwKoMLw

For further details, consult the three.js documentation:

:

.add ( object : Object3D, ... ) : this Adds object as child of this object. An arbitrary number of objects may be added. Any current parent on an object passed in here will be removed, since an object can have at most one parent.

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

Securing the connection between clients and servers through encryption

For my mobile client, I am using Xamarin, with node.js as my backend and MongoDB as the database. The main issue I am facing is how to securely store user data in the database. If I only do server-side encryption, there is a risk of hackers intercepting th ...

Angular - How child components can communicate with their parent components

I'm struggling to understand how to communicate between components and services. :( Even though I've read and tried a lot, some examples work but I still don't grasp why (?). My goal is to have one parent and two child components: dashboa ...

ES6 Promises have a curious ability to accurately retrieve values from custom JavaScript objects

I have developed a unique library that functions independently from the Promise API, yet achieves similar objectives. It utilizes window.requestAnimationFrame and fallbacks to setTimeout, having no similarities with Promises. Interestingly, it is compatibl ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

How to determine the presence of 'document' in Typecsript and NextJS

Incorporating NextJS means some server-side code rendering, which I can manage. However, I'm facing a challenge when trying to check for set cookies. I attempted: !!document && !!document.cookie as well as document !== undefined && ...

Utilizing Regular Input with Material-UI's Autocomplete Feature

Is there a way to replace TextField with a regular input in an Autocomplete? ...

Implementing an API call in Vue JS on the app.vue component of a single page application

My project is experiencing delays in API requests due to a large amount of data. I have tried adding a cache, but the page still appears white upon creation. I am considering moving the API call to app.vue to speed up the request. Is there a way to do this ...

What is the method to make a CSS selector avoid selecting a specific element?

Let's say I have a CSS style that looks like this: input.validation-passed {border: 1px solid #00CC00; color : #000;} The JavaScript validation framework I am using injects every input tag with a class="validation-passed". While this works fine ...

Executing mathematical calculations within a JavaScript object

Can an equation be executed inside an object? For instance: var taxes = { gst: '0.10', }; var prices = { first_key: '437.95', total_key: parseFloat(prices.first_key * taxes.gst).toFixed(2), ....... }, }; Or do I n ...

Trigger the callback function once the datatables DOM element has finished loading entirely

Hello there! I have a question regarding datatables. Is there any callback function available that is triggered after the datatables DOM element has finished loading? I am aware of the callbacks fnInitComplete, but they do not serve my purpose. Specificall ...

Initiating an Ajax POST request when the onblur() event is triggered

Having an issue with Ajax. I'm trying to submit a changed value from an input field on the onblur() event, but there's a flicker that's bothering me. When I enter a new value and click away, the old value briefly flashes back before changi ...

What is the best method for implementing click functionality to elements that share a common class using only pure JavaScript

I am struggling to figure out how to select specific elements with the same classes using only pure JavaScript (no jQuery). For example: <div class="item"> <div class="divInside"></div> </div> <div class= ...

How can I use a JavaScript or jQuery function to choose a specific audio track that is currently playing locally?

Currently, I have developed a music app that features local mp3 files triggered by clicking on divs which are linked to the audio using an onClick function with the play() method. Additionally, there is a scrolling screen that displays the song's arti ...

Exploring the concepts of nested If statements, for loops, and else if ordering within Javascript programming (FreeCodeCamp - lookUpProfile)

Currently tackling Free Code Camp's Javascript tutorials and encountering a roadblock on the "Contact Profile" <a href="https://www.freecodecamp.com/challenges/profile-lookup#?solution=%2F%2FSetup%0Avar%20contacts%20%3D%20%5B%0A%20%20%20%20%7B%0A%2 ...

What are the steps to implement an audio stream in a JavaScript React application?

I have been working on integrating a web dialer system into my JavaScript NextUI React app. After making some progress, I can successfully dial and hear my voice through the phone. However, I am encountering an issue where I cannot hear the other person sp ...

Mastering the utilization of custom input events in PrimeNG with Angular

I am currently working on an Angular 16 project. Within this project, I have implemented a number input field that is being validated using formControls. To make my work more efficient, especially since this input is used frequently, I decided to encapsula ...

Using jQuery to adjust the input value up and down with buttons

var number = 1; $("#counter input").attr('value', number); $("#increase").click(function(){ $("#counter input").attr('value', number++); }); $("#decrease").click(function(){ $("#counter input").attr('value', number--); }); ...

UTF-8 characters not displaying correctly in Python 3 when received through WebSocket?

I am encountering an issue with sending a JavaScript unicode star character. When interpreted by Python, the unicode characters are being displayed as the letter â, both in the console and log file. Furthermore, other unicode characters also seem to be ...

What is the importance of fulfilling a promise in resolving a response?

I have a promise structured as follows: let promise = new Promise((resolve, reject) => { axios.post("https://httpbin.org/post", params, header) .then(response => { resolve(Object.assign({}, response.data)); // resolve("aaaa"); ...

Is there a way to implement DnD functionality on a dynamically generated div element within an HTML page using Dojo

Is it possible to implement drag and drop functionality on dynamically generated div elements using Dojo? I have experimented with various methods to incorporate this feature. Below is a snippet of my code: var inputdiv = document.createElement('div& ...