Dynamically determine the position of an object within a three.js scene

Hello, I am a beginner exploring the world of threejs.

Currently, I have a scene set up with an object that can be freely moved along the XYZ Axis using TransformControls.js.

My goal is to retrieve the updated X,Y,Z position coordinates of this specific object within the scene whenever it is translated or moved by clicking and dragging on any axis (X,Y,Z).

Prior to rendering the scene, I typically use mesh.position.set( 0, 0, 0 ); to establish the initial position of the object. However, I am struggling to figure out how to obtain the dynamic position of the object as it moves within the scene.

Ultimately, my objective is to save the modified position coordinates after each transformation operation, allowing me to re-render the scene with the object positioned at the updated coordinates when the user returns to the page or initiates a page refresh.

If anyone has any suggestions or guidance on how to achieve this, I would greatly appreciate it.

Thank you for your help!

Answer №1

Utilizing THREE.TransformControls
involves a series of steps.

  1. Instantiate your THREE.TransformControls object
  2. Integrate it into your scene
  3. Attach it to the desired object for manipulation

var transControl = new THREE.TransformControls(camera, renderer.domElement);
scene.add(transControl);
// assuming you add "myObject" to your scene...
transControl.attach(myObject);
// and then later...
transControl.detatch();

Connecting the control to an object will introduce a manipulation "gizmo" in the scene. Dragging different parts of the gizmo will execute various transformations. Upon completing the transformation using the gizmo, inspecting mesh.position should reveal the updated position.

Further details for clarity:

The object's position will not be altered until you utilize the "gizmo" to move it. For example:

  1. Your object is located at (10, 10, 10) within the scene
  2. transControl.attach(yourObject)
  3. The "gizmo" emerges at (10, 10, 10)
  4. Your object remains at (10, 10, 10)
  5. Employ the "gizmo" to translate the object in the +Y direction
  6. Your object will now have an updated position
  7. console.log(yourObject.position.y > 10); // true

Answer №2

It's possible that I'm a bit late to the party, but there's a way to retrieve the most recent value by leveraging the 'objectChange' event in TransformControls.

Take a look at this sample code snippet:

const transformControls = new TransformControls(camera, renderer.domElement);

transformControls.addEventListener('objectChange', (e) => {
  console.log(e.target.object.position.x);
})

Answer №3

The initial response is inaccurate, the correct code snippet should read as follows:

const transformControls = new TransformControls(camera, renderer.domElement);

transformControls.addEventListener('objectChange', (e) => {
  console.log(e.target.object.position.x);
})

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

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

Experiencing a 400 error while transitioning from ajax to $http?

I am facing an issue while trying to make a GET request using $http instead of ajax. The call functions perfectly with ajax, but when attempting the same with $http, I encounter a 400 (Bad Request) error. I have referenced the Angular documentation and bel ...

What causes the lack of definition of this.state in this basic React component due to a contrived usage of bind?

This React application was created using create-react-app, with modifications made only to the file App.js. It serves as a test of my understanding of the bind method and its expected results. However, I am encountering an issue where despite binding the m ...

Hold off on loading the slick slider until we receive a response from the API call

My slick slider was working fine, but I encountered an issue where the slider would apply before receiving a response from an API request. This is my first function: fetchProducts () { this.getProducts ().then(response => { ...

The communication between a Firefox XUL extension and a webpage

Currently developing a Firefox XUL extension and in need of incorporating interaction between the web page and the extension. For instance, whenever a link is clicked on the page, I would like to trigger a function within the XUL extension. Is there any k ...

Guide to removing all elements belonging to a specific class on a webpage using Google Chrome

If I have elements on a website I am using with classes 'aaa', 'bbb', and 'ccc', and I want to delete or hide all elements with the class 'bbb', how can I accomplish this by changing attributes of elements directly o ...

Is there a way to verify if a checkbox has been checked?

Having trouble with this code: if($('#primayins').prop('checked')) { $("#tx_nm0x0_pricingplan").val(1); } else { $("#tx_nm0x0_pricingplan").val(2); } It keeps returning false consistently ...

Experiencing a specific error when utilizing the <v-file-input> component

I've integrated VueJS with vuetify. When I switch from an input tag to a v-file-input component, I encounter an error when triggering the function @click. Below is the script and template code: <script> import papa from "papaparse"; export ...

How can I capture the 'ended' event from an HTML5 video tag using Ember in a controller?

I am having an issue with an hbs file that contains an html5 video tag: <video id="externalVideo" controls loop> <source src="../assets/videos/test.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> I am ...

Tips for setting unique click functions for each face of a cube using React Three Fiber

Hey there! I have created a basic Cube component using react three fibre. import {useState,useRef} from 'react'; import { useFrame } from '@react-three/fiber'; const Box = ({props}) =>{ const ref = useRef() const [hove ...

What steps should I take to create an object that can be converted into a JSON schema like the one shown here?

I'm facing a rather simple issue, but I believe there's something crucial that I'm overlooking. My objective is to iterate through and add elements to an object in order to generate a JSON structure similar to the following: { "user1": ...

What is the name of the scrolling header effect achieved in the following?

I've been seeing a lot of people using a unique header effect lately and I'm curious to learn more about how it's done. Can anyone explain the process behind achieving this effect, what it's called, and if there are any good tutorials a ...

Display the HTML content once the work with AJAX and jQuery has been successfully finished

Below are the codes that I have created to illustrate my question. It's not a complete set of code, just enough to explain my query. The process goes like this: HTML loads -> calls ajax -> gets JSON response -> appends table row with the JSO ...

Ready for prerendering on a Gatsby site deployed with Netlify

We are encountering 504 errors on our Gatsby website hosted by Netlify. The problem stems from activating prerender.io, which often times out after 10 seconds, causing issues with Google bots detecting errors and consequently resulting in our ads being rej ...

Updating an array object property in state using Redux

I have a function that deals with action types and state updates. I decided to switch from using the "slice" method to the concat method for updating the state. The original code had a slice solution to update the object, but it didn't work as expecte ...

How to dynamically assign a name attribute to tags in a string using React and JavaScript

Streamlining the current blog post. If I have a string let someText = "<h1>test</h1><p>desc of test</p>" I want to use React or JavaScript to transform it into someText = "<h1 id="test">test</h1><p>desc of test ...

Is there a way to interrupt a function in jquery before it completes its execution?

I've created a program that activates a sequence of 5 lights and sounds when a button is clicked, continuously looping through the sequence. There's another button labeled "cancel" to stop the loop midway and reset everything to the initial state ...

Why aren't my Angular1.6 bindings functioning properly?

My goal is to grasp the new components, but I have a limited understanding of bindings and symbols. Despite my efforts, I can't seem to get ng-repeat to function with this code. I've experimented with controllerAs syntax, scope, changing the bin ...

The parsing of source maps fails due to issues with the .htaccess file

After analyzing the web page, I found that the .htaccess file contains the following code: RewriteEngine On RewriteBase / Options -MultiViews DirectorySlash Off # skip POST requests RewriteCond %{REQUEST_METHOD} POST RewriteRule ^ - [L] RewriteCond %{R ...

Steady Content of a Parallax Webpage

Hey there! I recently put together this awesome site and I'm facing a challenge with fixing text on the first slide, specifically the one featuring the Nike basketball. Right now, the text 'The first of its kind' is part of the background im ...