Determining the location of elements in Three.js: A step-by-step guide

As a newcomer to the world of 3D Graphics programming, I have started using Three.js to develop a software application that involves 3D bin packaging visualization. Currently, my code is focused on creating and positioning two elements.

var camera, scene, renderer;
var mesh, mesh2;
init();
function init() {
  camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
  camera.position.z = 800;
  scene = new THREE.Scene();
  var texture = new THREE.TextureLoader().load( 'https://threejs.org/examples/textures/crate.gif' );
  var geometry = new THREE.BoxBufferGeometry( 200, 200, 200 );
  var geometry2 = new THREE.BoxBufferGeometry( 200, 200, 200 );
  var material = new THREE.MeshBasicMaterial( {map:texture} );
  mesh = new THREE.Mesh( geometry, material );
  mesh2 = new THREE.Mesh( geometry2, material );
  mesh2.position.x = 170
  mesh2.position.y = -48
  mesh2.position.z = 100
  mesh.rotation.x = 0.45;
  mesh.rotation.y = 1;
  mesh2.rotation.x = 0.45;
  mesh2.rotation.y = 1;
  scene.add( mesh2 );
  scene.add( mesh );
  renderer = new THREE.WebGLRenderer( { antialias: true } );
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );
}

Currently, I have manually set the coordinates (170, -48, 100) to position the second cube. However, I believe there should be a more systematic approach to calculate these x, y, z values, especially when dealing with rotations (x=0.45, y=1). I am uncertain about the starting point for these calculations.

The challenge at hand involves determining a method to calculate and position cubes based on their dimensions (l1, w1, h1), (h2, w2, h2), and so on, along with their respective positions (x1, y1, z1), (x2, y2, z2), and beyond. How can these cubes be efficiently aligned and arranged, either near each other or stacked?

Answer №1

Transform mesh2 to be a descendant of mesh: mesh.add( mesh2 )

mesh2 will inherit the rotation of mesh and you can specify relative offsets to adjust its position within the parent's coordinate system.

Corrected example:

  mesh = new THREE.Mesh( geometry, material );
  mesh2 = new THREE.Mesh( geometry2, material );
  mesh2.position.x = 170
  //mesh2.position.y = -48
  //mesh2.position.z = 100
  mesh.rotation.x = 0.45;
  mesh.rotation.y = 1;
  //mesh2.rotation.x = 0.45;
  //mesh2.rotation.y = 1;
  scene.add( mesh );
  mesh.add( mesh2 ); // << ---- solution

Updated: It's also possible to achieve this without a parent-child relationship.

  let mesh = new THREE.Mesh( geometry, material );
  let mesh2 = new THREE.Mesh( geometry2, material );
  //  mesh2.position.x = 170
  //  mesh2.position.y = -48
  //  mesh2.position.z = 100
  mesh.rotation.x = 0.45;
  mesh.rotation.y = 1;
  mesh.updateMatrix(); // <<-- this is crucial, to update .position and .rotation values in the object transformation matrix.

  // mesh2.rotation.x = 0.45;
  // mesh2.rotation.y = 1;
  scene.add( mesh );

  // apply local transformations
  mesh2.applyMatrix(new THREE.Matrix4().makeTranslation(210, 0, 0));

  // apply transformations from mesh
  mesh2.applyMatrix(mesh.matrix);

  scene.add( mesh2 ); // << ---- add directly to Scene

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 a dynamic drop-down menu using a single database table in CodeIgniter

Table https://i.sstatic.net/yw7d0.jpg I need the district names to dynamically change based on the Category selection. For example, when I select Category 1 from the drop-down, only the district names under Category 1 should be displayed, and the same fo ...

Linking a background image in the body to a specific state in next.js

My aim is to create a pomodoro timer using Next.js and I'm trying to link the body's background image to a state. However, my code isn't functioning properly. This is the code I used to update the body style: import { VscDebugRestart } from ...

Importing GeoJSON data into Meteor's Leaflet

Recently diving into Meteor, I am on a mission to create my own customized version of this impressive example from leaflet incorporated into Meteor: Interactive Choropleth Map The implementation requires the use of this GeoJson Data file: us-states The o ...

The context parameter in Next Js' getStaticProps method gives back the values of "locales", "locale", and "defaultLocale" as undefined

Having an issue with the context parameter from Next Js's getStaticProps function. When I console log it, I am getting "{ locales: undefined, locale: undefined, defaultLocale: undefined }". Even though I am using getStaticProps inside the pages folde ...

The successful execution of one promise determines the outcome of the $q.all promise

I am currently dealing with a situation where I have three nested promises that I need to refactor into a single $q.all call. The current structure of the code looks like this: ds.saveData(data).then(function (result1){ someOtherVar = result1.Id; ...

Receive notifications when there are modifications in the JSON data using AJAX and jQuery

Below is the code snippet I created: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sample JSON Data Update</title> </head> <body> <style> span { font ...

Having trouble retrieving items from local storage in NextJS?

After logging in to my NextJS application, I store some user data in local storage. I'm attempting to create a small component that always shows the user's name. The problem I'm encountering is that sometimes it displays correctly and other ...

Delay calls to JavaScript functions, ensuring all are processed in order without any being discarded

Is there a way for a function to limit the frequency of its calls without discarding them? Instead of dropping calls that are too frequent, is it possible to queue them up and space them out over time, say X milliseconds apart? I've explored concepts ...

incorporating theme.spacing in the declaration of the theme

The theme setup that I am working with is as follows: export const themeDefault = createTheme({ themeName: 'Default (Mortgage Hub)', spacing: 4, ...typography, palette, components: { MuiButton: { styleOverrides: { root ...

What could be the reason behind the child component updating without triggering a re-render in Reactjs?

I am encountering an issue with my main component and child chart component. Even though the main component updates the state of the child chart component upon connecting to a websocket, the chart does not redraw as expected. Interestingly, when I click on ...

Is a single f.select impacting another f.select in the same form? (undesired)

I am facing an issue where adding a new HTML element like: <%= f.date_select :date, { id: "date-select"} %> is impacting my existing collection select: <%= f.collection_select :id, Customer.where(business_id: current_c ...

What is the best way to retrieve the nearest form data with jQuery after a child input has been modified?

I have a page with multiple forms, each containing several input checkboxes. When one of the form inputs changes, I want to gather all the parent form's data into a JSON array so that I can post it elsewhere. I'm having trouble putting the post ...

Showing the unique identifier instead of the actual data in HTML for a Firebase Object using Angularfire

Currently, I am utilizing AngularFire for a specific project. The structure of my firebase Object is as follows: { mainKey: { key1:value1, key2:value2 }, mainkey2: { key3:value3 } } The data has been inputted in a manner tha ...

Adjusting the size of several images individually with jquery

Currently, I am working on a jQuery script that enables me to resize any image by simply clicking on it. The goal is to have the ability to click on one image and resize it, then click on another image and resize it independently. Here is the code I have b ...

Execute the controller function with the value as a parameter

I encountered an issue while attempting to call a function in the c# controller and passing a value. The error message I received was: `'Unable to get property 'then' of undefined or null reference'. I also included the Driver Model but ...

Utilizing a React component for interactive button functionality

In my React app, I decided to enhance my buttons by incorporating images using SVG. After discovering that I needed a separate component for my SVG files, I came across this helpful resource and created my own <SVGIcon /> component. However, when at ...

Utilizing Vue.js i18n for a multi-line text display

Currently, I am implementing i18n single file component in order to provide translation support for my application. In order to achieve this, I have been utilizing the i18n tag as shown below: <i18n> { "fr": { "text": "Lore ...

Tips for dynamically populating an HTML table with data from a JSON array using JQuery

I have generated an HTML table <table id="top_five_table"> <tr> <td> </th> <th>URL</th> <th width="90">Total Hits</th> <th width="380">Percentage of all Hits</th> </tr> <tr> ...

Updates to the AngularJS model are not appearing in the user interface

Despite executing the controller code, the values in the UI remain unchanged. The initial values are displayed without any issue. I've attempted to call $scope.$apply() at the end of each function (submit and transfer), but it didn't resolve the ...

What steps can be taken to address the issue of the body-parser module being disabled in a node

My API is not functioning properly and I have observed that the body-parser module seems to be disabled in some way. Despite my efforts, I have been unable to find any information on this issue. Please refer to the image attached below for further details. ...