Tom Wong
Tom Wong

Reputation: 33

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

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

Upvotes: 3

Views: 2659

Answers (1)

Mugen87
Mugen87

Reputation: 31026

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 );

Upvotes: 2

Related Questions