Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three.js GetWorldPosition() / localToWorld() position not correct?

Tags:

three.js

I try to get worldposition of some child object using raycast, and then position a cube in exact position as my intersected object , but the placement is not same as what i expected , needed help, below is the code im using

  raycaster.setFromCamera(new THREE.Vector2(), camera);
  const intersects = raycaster.intersectObjects( scene.children, true );
  if(intersects.length > 0){
    var object = intersects[0].object;
    var cube = new THREE.Mesh( new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshNormalMaterial() );

    var pos = new THREE.Vector3();
    object.localToWorld( pos );
    cube.position.copy( pos );
    scene.add( cube );

when i add the cube into the scene the cube appear in other position , please let me know what am i missing here , thank you.

Edited below is my screenshot enter image description here

like image 566
Tom Wong Avatar asked Dec 05 '25 18:12

Tom Wong


1 Answers

Object3D.localToWorld() converts the given vector to world space. Since you pass in the null vector, the result is not as expected. Do this instead:

var pos = new THREE.Vector3();
pos.copy( object.position );
object.localToWorld( pos );

Or in a more readable fashion:

var pos = new THREE.Vector3();
object.getWorldPosition( pos );
like image 100
Mugen87 Avatar answered Dec 10 '25 03:12

Mugen87



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!