Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get object position in a three.js scene dynamically

I am new to threejs.

I have scene with an object in it which we can move around the scene on all the XYZ Axis using TransformControls.js.

When I translate/move the object inside the scene using mouse click and drag on any of the axis (i.e X,Y,Z). I want to get the updated X,Y,Z position co-ordinates of that particular object inside the scene.

I use mesh.position.set( 0, 0, 0 ); to set position of the object prior rendering the scene, But I am not able to find how to get the dynamic position of an object inside a scene.

Eventually I want to save the updated position co-ordinates after the transform operation and re-render the scene with the object at the updated position co-ordinates when the user comes back to the page or does a page refresh.

Any pointers would be very helpful.

Thank you

like image 218
Taher Avatar asked Dec 17 '25 23:12

Taher


2 Answers

THREE.TransformControls requires a few steps to use.

  1. Create your THREE.TransformControls object
  2. Add it to your scene
  3. Attach it to the object you wish to manipulate

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

Attaching the control to an object will insert a manipulation "gizmo" into the scene. Dragging the various parts of the gizmo will perform different kinds of transformations. After you are done transforming the part with the gizmo, checking mesh.position should reflect the new position.

Additional information for clarity:

The position of the object will not be updated until you use the "gizmo" to move it. Example:

  1. Your object is in the scene at (10, 10, 10)
  2. xformControl.attach(yourObject)
  3. The "gizmo" is created at (10, 10, 10)
  4. Your object remains at (10, 10, 10)
  5. Use the "gizmo" to translate the object in +Y direction
  6. Your object will now have an updated position
  7. console.log(yourObject.position.y > 10); // true
like image 89
TheJim01 Avatar answered Dec 20 '25 14:12

TheJim01


I might be too late, but you can get the updated value by using TransformControls' objectChange event.

Example code:

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

transformControls.addEventListener('objectChange', (e) => {
  console.log(e.target.object.position.x);
})
like image 44
Kenny Avatar answered Dec 20 '25 14:12

Kenny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!